

import 'dart:async';

import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/model_utils.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/common/widget/rotate_arrow_widget.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/main/application.dart';
import 'package:bike_ride/model/pay/view_model/pay_box_vm.dart';
import 'package:bike_ride/res/IconFont.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pretty_qr_code/pretty_qr_code.dart';

/// 支付弹窗页
class PayBoxView extends BaseStatefulPage<PayBoxViewModel> {
  final Map<String,dynamic> arguments;
  const PayBoxView({required this.arguments,super.key});

  @override
  PayBoxViewState createState() => PayBoxViewState();
}

class PayBoxViewState
    extends BaseStatefulPageState<PayBoxView, PayBoxViewModel> {

  late Timer timer;
  int _countdown = 0;

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initAttribute() {
    timer = Timer.periodic(const Duration(seconds: 2), (timer) {
      //定时请求次数30次
      if(viewModel!.startTimer){
        if(_countdown < 30){
          _countdown++;
          viewModel!.getOverseasPayStatus();
        }else{
          viewModel!.startTimer = false;
          EasyLoading.showError(S.current.payOverTime);
          Navigator.pop(context);
        }
      }else{
        _countdown = 0;
      }
    });
  }

  @override
  void dispose() {
    if(timer.isActive){
      timer.cancel();
    }
    super.dispose();
  }

  @override
  void initObserver() {
  }

  @override
  PayBoxViewModel viewBindingViewModel() {
    return PayBoxViewModel()..viewState = this;
  }

  @override
  Widget appBuild(BuildContext context) {
    return _RidingPayOrderBox(viewModel: viewModel!,);
  }



  void successCallBack(){
    ///二维码支付-关闭弹窗
    final keyStateMounted = erCodeKey.currentState?.mounted??false;
    if(keyStateMounted){
      Navigator.pop(context);
    }
    ///在线支付
    //Nothing to do
    Navigator.pop(context);
  }
  /********************打开第三方网页支付方式************************************************************************/
  void navigateToPayView(String payUrl) async{
    NavigatorUtil.push(context, Routers.webViewPage,arguments: {
      'url': payUrl,
    }).then((_){
      viewModel!.getOverseasPayStatus().then((value){
        if(value == false){
          viewModel!.startTimer = true;
        }
      });
    });
  }
  /********************二维码支付方式************************************************************************/
  final erCodeKey = GlobalKey();
  void showPayErCodeDialog(){
    viewModel!.startTimer = true;
    showAlertDialog(
      context: context,
      title: S.current.pleasePaySco,
      confirmName: S.current.mePayed,
      cancelName: S.current.dealLater,
      onWillPopBol: false, //避免手机误触，退出支付二维码
      content: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(14.rpx),
        ),
        child: Center(
            child: PrettyQr(
              key: erCodeKey,
              data: viewModel!.overseasPayM!.qrCode!.split('code=').last,
              size: 400.rpx,
              errorCorrectLevel: QrErrorCorrectLevel.H,
              roundEdges: true,
            )),
      ),
      onCancel: () {
        viewModel!.overseasPayM = null;
        EasyLoading.showToast(S.current.payNoFinish);
        viewModel!.startTimer = false;
        Navigator.of(context).pop();
      },
      onConfirm: () {
        viewModel!.getOverseasPayStatus().then((value) {
          if(value){
            viewModel!.startTimer = false;
            Navigator.of(context).pop();
            Future.delayed(const Duration(milliseconds: 500),(){
              Navigator.of(context).pop();
            });
            EasyLoading.showSuccess('success');
          }else{
            EasyLoading.showError(S.current.payResponse1);
          }
        });
      },
    );
  }

}
class _RidingPayOrderBox extends StatefulWidget {
  final PayBoxViewModel viewModel;
  const _RidingPayOrderBox({required this.viewModel});

  @override
  State<_RidingPayOrderBox> createState() => _RidingPayOrderBoxState();
}

class _RidingPayOrderBoxState extends State<_RidingPayOrderBox> {
  ///支持的支付方式
  final List<String> _payTypeList = [S.current.payBalance, S.current.payOpenPay, /*S.current.payByFiuu, S.current.payByMPT*/];
  String _payType = S.current.payBalance;

  @override
  void initState() {
    super.initState();
    // if(EnvConfig.payChanelByMPT){
    //   _payTypeList.add(S.current.payByMPT);
    // }else{
    //   //默认马来fiuu支付
    //   _payTypeList.add(S.current.payByFiuu);
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 28.rpx, horizontal: 28.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(40.rpx),
          topRight: Radius.circular(40.rpx),
        ),
        color: ColorStyles.color_FFFFFF,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildTitle(S.current.pay),
          Padding(padding: EdgeInsets.symmetric(vertical: 10.rpx),child: const Divider(color: ColorStyles.color_F3F4F5,),),

          Row(
            children: [
              Text(S.current.orderAmount,style: TextStyle(color: ColorStyles.color_333333,fontSize: 32.rpx),),
              const Spacer(),
              GestureDetector(
                onTap: (){
                  showDialog();
                },
                child: Row(
                  children: [
                    Text('￥${widget.viewModel.unPayInfoM?.costPrice??''}',style: TextStyle(color: ColorStyles.color_333333,fontSize: 32.rpx),),
                    Icon(IconFont.iconjiantouyou,color: ColorStyles.color_666666,size: 28.rpx,),
                  ],
                ),
              )
            ],
          ),

          SizedBox(height: 28.rpx,),
          Container(
            padding: const EdgeInsets.only(left: 4),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              physics: const BouncingScrollPhysics(),
              child: Wrap(
                spacing: 2,
                runSpacing: 16.rpx,
                children: [
                  _buildHelpItem(S.current.chargeStandard, () {
                    NavigatorUtil.push(context, Routers.freightView);
                  }),
                  _buildHelpItem(S.current.feedback, () {
                    NavigatorUtil.push(context, Routers.faultReportView,arguments: {'vid':widget.viewModel.unPayInfoM?.vid});
                  }),
                  // _buildHelpItem('费用申诉', () {
                  // }),
                  _buildHelpItem(S.current.customerService, () {
                    NavigatorUtil.push(context, Routers.webViewPage,arguments: {'url':'${AccountManager.baseUrl}/bluetooth_rule.html'});
                  }),
                ],
              ),
            ),
          ),

          /// 预计需支付：前端动态计算，选择骑行卡后变化
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Text('${S.current.payPredict}：￥',style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_666666),),
              Text('${widget.viewModel.unPayInfoM?.amount??''}',style: TextStyle(fontSize: 32.rpx,fontWeight: FontWeight.w500),)
            ],
          ),

          ///选择支付方式
          Padding(padding: EdgeInsets.symmetric(vertical: 10.rpx),child: const Divider(color: ColorStyles.color_F3F4F5,),),
          ..._payTypeList.map((e) {
            String centerText = '';
            String iconPath = '';
            final addT = (widget.viewModel.discountStatM?.balanceAmount??0) + (widget.viewModel.discountStatM?.giftBalanceAmount??0);
            if(e == S.current.payBalance){
              centerText = '￥${parseToMoney(addT)}';
              iconPath = 'assets/applet/ic_balance.png';
            }else if(e == S.current.payOpenPay){
              iconPath = 'assets/applet/ic_wechat.png';
            }else if(e == S.current.payByFiuu){
              iconPath = 'assets/applet/icon_fiuu.png';
            }else if(e == S.current.payByMPT){
              iconPath = 'assets/applet/icon_mpt.png';
            }
            return _buildPayType(iconPath, e,centerText: centerText,isSelected: e == _payType);
          }).toList(),

          ///支付按钮
          XbButton(
            isDefault: false,
            width: MediaQuery.of(context).size.width,
            child: Text('${S.current.payConfirm}￥${widget.viewModel.unPayInfoM?.costPrice}'),
            onPressed: ()async{
              if(_payType == S.current.payBalance){
                ///余额支付
                final result = await widget.viewModel.balancePay(widget.viewModel.orderId, widget.viewModel.unPayInfoM?.costPrice);
                if(result && mounted){
                  Navigator.pop(context);
                }
              }else if(_payType == S.current.payOpenPay){
                await widget.viewModel.getOverseasOpenPay(widget.viewModel.orderId, widget.viewModel.unPayInfoM?.costPrice);
              }else if(_payType == S.current.payByFiuu){
                ///马来fiuu在线支付
                await widget.viewModel.getOverseasH5Pay(widget.viewModel.orderId,widget.viewModel.unPayInfoM?.costPrice,payChanel: 12);
              }else if(_payType == S.current.payByMPT){
                ///印尼MPT在线支付
                await widget.viewModel.getOverseasH5Pay(widget.viewModel.orderId,widget.viewModel.unPayInfoM?.costPrice,payChanel: 13);
              }
            },
          )
        ],
      ),
    );
  }

  Widget _buildPayType(String iconPath,String title,{String centerText = '',bool isSelected = false}){
    return Row(
      children: [
        Image.asset(iconPath,width: 50.rpx,height: 50.rpx,fit: BoxFit.cover,),
        SizedBox(width: 28.rpx,),
        Text(title,style: TextStyle(fontSize: 28.rpx),),
        if(centerText.isNotEmpty)
          ...[
            SizedBox(width: 20.rpx,),
            Text(centerText,style: TextStyle(fontSize: 28.rpx),),
          ],
        const Spacer(),
        IconButton(onPressed: (){
          setState(() {
            _payType = title;
          });
        }, icon: isSelected?Icon(IconFont.iconcheckCircleFilled,color: Theme.of(context).colorScheme.primary,):const Icon(IconFont.iconaFill32,color: ColorStyles.color_999999,)),
      ],
    );
  }


  Widget _buildHelpItem(String text, Function() onPress) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        padding: EdgeInsets.only(
            right: 16.rpx, left: 16.rpx, top: 8.rpx, bottom: 8.rpx),
        margin: EdgeInsets.only(right: 8.rpx),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.rpx),
          border: Border.all(color: ColorStyles.color_EEEEEE),
        ),
        child: Text(text,
            style:
            TextStyle(fontSize: 24.rpx, color: ColorStyles.color_999999)),
      ),
    );
  }

  Widget _buildTitle(String title){
    return Container(
      height: 40.rpx,
      child: Stack(
        children: [
          Positioned(left: -20.rpx,top: 0,bottom: 0,child: IconButton(
            icon: Icon(IconFont.iconclosel,color: ColorStyles.color_333333,size: 32.rpx,),
            onPressed: (){
              Navigator.pop(context);
            },
          ),),
          Center(
            child: Text(title,style: TextStyle(color: ColorStyles.color_333333,fontSize: 32.rpx)),
          ),
        ],
      ),
    );
  }


  void showDialog(){
    showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return _BuildDetail(viewModel: widget.viewModel);
      },
    );
  }

}


class _BuildDetail extends StatefulWidget {
  final PayBoxViewModel viewModel;
  const _BuildDetail({required this.viewModel});

  @override
  State<_BuildDetail> createState() => _BuildDetailState();
}

class _BuildDetailState extends State<_BuildDetail> {
  bool isExpand1 = false;
  bool isExpand2 = false;
  bool isExpand3 = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 28.rpx),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTitle(S.current.payFeeDetail),

          Container(
            color: ColorStyles.color_F3F4F5,
            padding: EdgeInsets.symmetric(horizontal: 28.rpx),
            child: Column(
              children: [
                _buildContainer(
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        _buildInfoRow(S.current.orderInfo,'',rightWidget: RotateArrowWidget(
                          isRotate: isExpand1,
                          onChange: (value) {
                            setState(() {
                              isExpand1 = value;
                            });
                          },
                        )),
                        if(isExpand1)
                          ...[
                            _buildInfoRow(S.current.orderId, widget.viewModel.unPayInfoM?.orderId??'-'),
                            _buildInfoRow(S.current.vehicleNumber,widget.viewModel.unPayInfoM?.vid??'-'),
                            _buildInfoRow(S.current.orderAmount,'${widget.viewModel.unPayInfoM?.costPrice??'-'}${S.current.yuan}',rightWidget: RotateArrowWidget(
                              isRotate: isExpand2,
                              onChange: (value) {
                                setState(() {
                                  isExpand2 = value;
                                });
                              },
                            )),
                            if(isExpand2)
                              Container(
                                padding: EdgeInsets.all(8.rpx),
                                decoration: BoxDecoration(
                                    color: const Color(0xFFF8FaFF),
                                    borderRadius: BorderRadius.all(Radius.circular(16.rpx))
                                ),
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _buildInfoRow(S.current.startPrice,'${widget.viewModel.unPayInfoM?.properties?.payByStart??0}${S.current.yuan}',
                                    ),
                                    _buildInfoRow(S.current.timeFee,'${widget.viewModel.unPayInfoM?.exceedPrice??0}${S.current.yuan}',
                                    ),
                                  ],
                                ),
                              ),
                          ]
                      ],
                    )
                ),

                _buildContainer(
                    Column(
                      children: [
                        _buildInfoRow(S.current.rideTime, durationTransform(((widget.viewModel.unPayInfoM?.ridingTime??0) * 60).toInt(),isEasy: true,needZeroFill: false), rightWidget:RotateArrowWidget(
                          isRotate: isExpand3,
                          onChange: (value) {
                            setState(() {
                              isExpand3 = value;
                            });
                          },
                        )
                        ),

                        if(isExpand3)
                          Container(
                            padding: EdgeInsets.all(8.rpx),
                            decoration: BoxDecoration(
                                color: const Color(0xFFF8FaFF),
                                borderRadius: BorderRadius.all(Radius.circular(16.rpx))
                            ),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Icon(Icons.radio_button_on,color: Theme.of(context).colorScheme.primary,),
                                    SizedBox(width: 18.rpx,),
                                    Text(formatTimestamp(widget.viewModel.unPayInfoM?.startTime),style: TextStyle(color: ColorStyles.color_999999,fontSize: 22.rpx),),
                                  ],
                                ),
                                SizedBox(height: 8.rpx,),
                                Row(
                                  children: [
                                    Icon(Icons.radio_button_on,color: Theme.of(context).colorScheme.primary,),
                                    SizedBox(width: 18.rpx,),
                                    Text(formatTimestamp(widget.viewModel.unPayInfoM?.endTime),style: TextStyle(color: ColorStyles.color_999999,fontSize: 22.rpx),),
                                  ],
                                ),
                              ],
                            ),
                          )
                      ],
                    )
                ),

                _buildContainer(
                    _buildInfoRow(S.current.rideMiles, '${widget.viewModel.unPayInfoM?.mile??0}km')
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildTitle(String title){
    return Container(
      padding: EdgeInsets.symmetric(vertical: 28.rpx,horizontal: 28.rpx),
      decoration: BoxDecoration(
          color: ColorStyles.color_FFFFFF,
          borderRadius: BorderRadius.only(topLeft: Radius.circular(40.rpx),topRight: Radius.circular(40.rpx))
      ),
      child: Stack(
        children: [
          Positioned(left: -20.rpx,top: 0,bottom: 0,child: IconButton(
            icon: Icon(IconFont.iconclosel,color: ColorStyles.color_333333,size: 32.rpx,),
            onPressed: (){
              Navigator.pop(context);
            },
          ),),
          Center(
            child: Text(title,style: TextStyle(color: ColorStyles.color_333333,fontSize: 32.rpx)),
          ),
        ],
      ),
    );
  }

  Widget _buildContainer(Widget child){
    return Container(
      margin: EdgeInsets.only(top: 22.rpx),
      padding: EdgeInsets.all(16.rpx),
      decoration: BoxDecoration(
        color: ColorStyles.color_FFFFFF,
        borderRadius: BorderRadius.circular(10.rpx),
      ),
      child: child,
    );
  }

  Widget _buildInfoRow(
      String left,
      String right, {
        Widget? rightWidget,
      }) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8.rpx),
      child: Row(
        children: [
          Text(
            left,
            style: TextStyle(
              fontSize: 26.rpx,
              color: ColorStyles.color_999999,
            ),
          ),
          const Spacer(),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                right,
                style: TextStyle(
                  fontSize: 26.rpx,
                  color: ColorStyles.color_999999,
                ),
              ),
              if (rightWidget != null) rightWidget,
            ],
          )
        ],
      ),
    );
  }
}